package com.sxt.shiro;

import com.sxt.shiro.domain.User;
import com.sxt.shiro.realm.UserRealm;
import com.sxt.shiro.utils.Md5utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestAuthenticationApp {

    private static final transient Logger log = LoggerFactory.getLogger(TestAuthenticationApp.class);

    public static void main(String[] args) {
        log.info("myfirstshiroapplication");
        String username="zhangsan";
        String password="123456";
        //1.创建安全管理器的工厂对象
        Factory<SecurityManager> factory=  new IniSecurityManagerFactory("classpath:shiro.ini");
        //2.使用工厂创建安全管理器
        DefaultSecurityManager securityManager = (DefaultSecurityManager) factory.getInstance();
        UserRealm userRealm = new UserRealm();
        securityManager.setRealm(userRealm);
        //3.把当前的安全管理器绑定到当前的线程
        SecurityUtils.setSecurityManager(securityManager);
        //4.使用SecurityUtils.getSubject()得到主体对象
        Subject subject = SecurityUtils.getSubject();
        //5.封装用户名和密码
        String passwordMd5 = Md5utils.md5(password, username);
        System.out.println(passwordMd5);
        UsernamePasswordToken token = new UsernamePasswordToken(username,passwordMd5);
        //6.得到认证
        try {
            subject.login(token);
            System.out.println("通过认证");
        } catch (AuthenticationException e) {
            System.out.println("用户名或密码不正确");
        }
        boolean authenticated = subject.isAuthenticated();
        System.out.println(authenticated);
        //判断是否有角色
        boolean role1 = subject.hasRole("role2");
        System.out.println(role1);
        //判断是否有权限
        boolean permitted = subject.isPermitted("user:update");
        System.out.println(permitted);
    }
}
